package com.dhq.junit;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;

import com.dhq.utils.sqlserverUtils;

/**
 * @author denghuanqing
 *	query sqlserver careate index
 */
public class TestSqlserver {

	@Test
	public void createIndex() throws SQLException, SolrServerException, IOException {
		
		int count=0;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr");

		Connection sqlServerConnection = sqlserverUtils.getSqlServerConnection(
				"sogoufile", "sa", "123456");
		PreparedStatement ps = sqlServerConnection
				.prepareStatement("select 分类号,中文关键词 from keywords");
		ResultSet resultSet = ps.executeQuery();

		while (resultSet.next()) {
			// 创建一个文档对象
			SolrInputDocument document = new SolrInputDocument();
			
			document.addField("id", resultSet.getString("分类号"));
			document.addField("name", resultSet.getString("中文关键词"));
			
			// 向solr中添加记录
			solrServer.add(document);
			/*count++;
			if (count%10000==0) {
				System.out.println("count"+count+df.format(System.currentTimeMillis()));
			}*/
// http://localhost:8080/solr/update/?stream.body=<delete><query>*:*</query></delete>&stream.contentType=text/xml;charset=utf-8&commit=true
		}

		// 提交修改
		solrServer.commit();
		System.out.println("数据导入完成！");
	}
	
		@Test
		public void testSearch() throws SolrServerException {

			SolrServer solr = new HttpSolrServer("http://localhost:8080/solr");
			// 查询对象
			SolrQuery query = new SolrQuery();
			//设置查询条件,名称“q”是固定的且必须 的
			query.set("q", "name:中国");
			// 请求查询
			QueryResponse response = solr.query(query);

			// 查询结果
			SolrDocumentList docs = response.getResults();
			// 查询文档总数
			System.out.println("查询文档总数" + docs.getNumFound());

			for (SolrDocument doc : docs) {
				Object id = doc.getFieldValue("id");
				String name = (String) doc.getFieldValue("name");
				System.out.println("=============================");
				System.out.println(id+" === "+name);
			}
		}

}
